package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;

@Component
public class Cache {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //redis设置过期时间
    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    //redis设置逻辑过期时间
    public void setlogical(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData),time,unit);
    }
    //互斥锁解决缓存穿透
    public <R,ID>R lock(String bkey, ID id, Class<R> type, Function<ID,R> find,Long time,TimeUnit unit){
        String key=bkey+id;
        //查询redis是否存在
        String s = stringRedisTemplate.opsForValue().get(key);
        if (!StrUtil.isBlank(s)){
            R r = JSONUtil.toBean(s, type);
            return r;
        }
        if (s!=null){
            return null;
        }
        //查询数据库
        R apply = find.apply(id);
        if (apply==null){
            //储存空字符串
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //储存到redis
        //二次检查
        s = stringRedisTemplate.opsForValue().get(key);
        if (!StrUtil.isBlank(s)){
            R r = JSONUtil.toBean(s, type);
            return r;
        }
        set(key,apply,time,unit);
        return apply;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
    //逻辑法解决缓存穿透
    public <R,ID>R logical(String bkey, ID id, Class<R> type, Function<ID,R> find,Long time,TimeUnit unit){
        String key=bkey+id;
        //查询redis是否存在
        String s = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(s)){
            return null;
        }
        //有，查询redis是否过期
        RedisData redisData = JSONUtil.toBean(s, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //未过期
        if (expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        //过期获取锁
        boolean tryLock = tryLock(LOCK_SHOP_KEY + id);
        if (tryLock){
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R apply = find.apply(id);
                    setlogical(key,apply,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(LOCK_SHOP_KEY + id);
                }
            });
        }
        return r;
    }

    //使用redis中的setnx实现互斥锁。
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //潜在的NullReferenceException，如果装箱的对象是null,那么在拆箱时可能会抛出NullReferenceException
        return BooleanUtil.isTrue(flag);
    }
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}

